<?php

namespace app\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
use app\common\View;

class Admin implements MiddlewareInterface
{
    public function process(Request $request, callable $next): Response
    {
        //检查登录
        $User = session('user');
        if (!isset($User) && (getController() != 'LoginController')) {
            return error('请先登录', route('admin.login.log'));
        } else {
            if (getController() != 'LoginController') {
                //鉴权
                $UserAuth = session('auth');
                if ($UserAuth["rid"] > 0) {
                    $AuthArr = json_decode($UserAuth["auth"], true); //已拥有的权限
                    $class = new \ReflectionMethod('\\' . $request->controller, $request->action);
                    $attributes = $class->getAttributes(\app\common\Attribute::class);
                    $AuthThen = $attributes[0]->newInstance()->fun(); //当前权限
                    if ($AuthThen["isAuth"]) { //需要鉴权
                        $suffix = config('app.controller_suffix', ''); //控制器后缀
                        $controller = str_replace($suffix, "", getController());

                        if (!in_array("{$controller}@{$request->action}", $AuthArr)) {
                            return error("您没有该权限", "#");
                        }
                    }
                }
            }
            View::assign("user", $User);
        }
        return $next($request);
    }
}
